<template>
    <el-card style="margin-bottom: 20px;">
        <!-- 查询 -->
        <el-form :model="state.queryParams" ref="queryForm" :inline="true">
            <el-form-item v-for="(item, index) in filteredQueryData" :label="item.columnTittle" :prop="item.fieldName"
                :key="index">
                <el-input v-model="state.queryParams[item.fieldName]" :placeholder="'请输入' + item.columnTittle" clearable
                    @keyup.enter.native="$emit('handleQuery', state.queryParams)" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="$emit('handleQuery', state.queryParams)">
                    <SvgIcon name="elementSearch" />搜索
                </el-button>
                <el-button @click="resetQuery">
                    <SvgIcon name="elementRefresh" />
                    重置
                </el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <div v-loading="loading" style="min-height:600px">
        <el-card class="box-card" v-if="filteredListData.length">
            <template #header>
                <div class="card-header">
                    <span class="card-header-text">{{ listName }}</span>
                    <div>
                        <el-button type="primary" plain v-auth="`${className}:add`" @click="$emit('onOpenAddModule')">
                            <SvgIcon name="elementPlus" />新增
                        </el-button>
                        <el-button type="danger" plain v-auth="`${className}:batchDelete`" :disabled="state.multiple"
                            @click="onTableRowDel">
                            <SvgIcon name="elementDelete" />删除
                        </el-button>
                    </div>
                </div>
            </template>
            <!--数据表格-->

            <el-table :data="tableData" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column v-for="(item, index) in filteredListData" :key="index" :label="item.columnTittle"
                    :width="item.htmlWidth ? item.htmlWidth : ''" :prop="item.fieldName">
                    <template #default="scope" v-if="$slots[item.fieldName]">
                        <slot :name="item.fieldName" :row="item"></slot>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                    <template #default="scope">
                        <span>{{ dateStrFormat(scope.row.createTime) }}</span>
                    </template>
                </el-table-column> -->
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <div style="display: flex;align-items: center;justify-content: center;gap: 10px;">
                            <div>
                                <el-tooltip class="box-item" effect="dark" content="编辑" placement="top-start">
                                    <el-button type="primary" size="small" circlesize="small" circle
                                        v-auth="`${className}:edit`" @click="$emit('onOpenEditModule', scope.row)">
                                        <SvgIcon :size="12" name="elementEdit" />
                                    </el-button>
                                </el-tooltip>
                            </div>
                            <div>
                                <slot name="listBtn" :row="scope.row"></slot>
                            </div>
                            <div>
                                <el-tooltip class="box-item" effect="dark" content="删除" placement="top-start">
                                    <el-button type="danger" size="small" circle v-auth="`${className}:delete`"
                                        @click="onTableRowDel(scope.row)">
                                        <SvgIcon :size="12" name="elementDelete" />
                                    </el-button>
                                </el-tooltip>
                            </div>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页设置-->
            <div v-show="total > 0">
                <el-divider></el-divider>
                <el-pagination background :total="total" :current-page="state.queryParams.pageNum"
                    :page-size="state.queryParams.pageSize" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>
    </div>
</template>

<script lang="ts" setup name="Partner">
import {
    reactive,
    onMounted,
    getCurrentInstance,
    onUnmounted,
    computed,
    defineProps,
    defineEmits,
    watch
} from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { del, get } from "@/api/public/basic";

const { proxy } = getCurrentInstance() as any;

// props
const props = defineProps({
    listId: {
        type: String,
        default: ''
    },
    className: {
        type: String,
        default: ''
    },
    listName: {
        type: String,
        default: ''
    },
    tableData: {
        type: Array,
        default: () => []
    },
    loading: {
        type: Boolean,
        default: true
    },
    // 总条数
    total: {
        type: Number,
        default: 0
    },
    // 当前表单的编码名
    mainKeyName: {
        type: String,
        default: ''
    }
});
// emits
const emit = defineEmits(['handleQuery', 'onOpenEditModule', 'onOpenAddModule',])
const state = reactive({
    tableStructData: [],
    // 选中数组
    ids: [],
    // 非单个禁用
    single: true,
    // 非多个禁用
    multiple: true,
    // 查询参数
    queryParams: {
        // 页码
        pageNum: 1,
        // 每页大小
        pageSize: 10,
    },
});


// 可搜索的字段
const filteredQueryData = computed(() => {
    return state.tableStructData.filter((item: any) => item.isQuery) || [];
});

// 列表展示字段
const filteredListData = computed(() => {
    return state.tableStructData.filter((item: any) => item.isList) || [];
})


// 监听props.list
watch(
    () => props.listId,
    () => {
        if (!props.listId) return
        // 获取table struct
        const tableStructId = 'hQrMVhPV7LY'
        get({
            pageNum: 1,
            pageSize: 50,// 暂时默认
            listId: props.listId,
        }, tableStructId).then((res: any) => {
            if (res.status == 0) {
                const arr = res.data.result.map((item: any) => {
                    if (item.isQuery) {
                        state.queryParams[item.fieldName] = undefined;
                    }
                    return item
                })
                arr.sort(compareSorts)
                state.tableStructData = arr
                emit('handleQuery', state.queryParams)
            }
        })
    },
    { immediate: true }
);

/**比较两个对象的 sort 属性*/
const compareSorts = (a: any, b: any) => {
    // 如果 sort 属性为 null，则将其视为无穷大
    if (a.sort === null || b.sort === null) {
        return 0; // 不参与排序
    }
    // 比较 sort 属性
    return a.sort - b.sort;
};


/** 重置按钮操作 */
const resetQuery = () => {
    state.tableStructData.forEach((item: any) => {
        if (item.isQuery) {
            state.queryParams[item.columnName] = undefined;
        }
        return item
    })
    emit('handleQuery', state.queryParams)
};

const handleCurrentChange = (val: number) => {
    state.queryParams.pageNum = val
    emit('handleQuery', state.queryParams)
}
const handleSizeChange = (val: number) => {
    state.queryParams.pageSize = val
    emit('handleQuery', state.queryParams)
}

/** 删除按钮操作 */
const onTableRowDel = (row: any,) => {
    const ids = row[props.mainKeyName] ? [row[props.mainKeyName]] : state.ids;

    ElMessageBox({
        message: '是否确认删除的数据项?',
        title: "警告",
        showCancelButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(function () {
        return del({ [props.mainKeyName]: ids }, props.listId).then(() => {
            emit('handleQuery', state.queryParams)
            ElMessage.success("删除成功");
        });
    });
};
// 多选框选中数据
const handleSelectionChange = (selection: any) => {

    state.ids = selection.map((item: any) => {
        return item[props.mainKeyName]
    });

    state.single = selection.length != 1;
    state.multiple = !selection.length;
};
// 页面加载时
onMounted(() => {

});
// 页面卸载时
onUnmounted(() => {
    proxy.mittBus.off("onEditModule");
});
</script>
